package com.donleo.stmg.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @author liangd
 * date 2020-12-10 16:00
 * code 跨域配置
 * .@Order 注解用来声明组件的顺序，值越小，优先级越高，越先被执行/初始化。如果没有该注解，则优先级最低。
 */
@Configuration
@Order(1)
public class FilterConfig {
    /**
     * SpringBoot升级2.4.0 需要将addAllowedOrigin替换成.addAllowedOriginPattern
     */
    private CorsConfiguration buildConfig(){
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 允许任何的head头部
        corsConfiguration.addAllowedHeader("*");
        // 允许任何域名使用 corsConfiguration.addAllowedOrigin("*")
        corsConfiguration.addAllowedOriginPattern("*");
        // 允许任何的请求方法
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }
    /**
     * 添加CorsFilter拦截器，对任意的请求使用
     * @return CorsFilter
     */
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }

}
